package git.bankview.wl.common;

import java.util.*;

import laya.semi.process.*;

//import org.apache.log4j.Logger;

public class CharsetEncoder
	implements IGenericClassActivity
{
//	private static Logger log = Logger.getLogger(CharsetEncoder.class);

	public void execute(IProcessContext oCtx)
		throws Exception
	{
		String[] vParam = oCtx.getActivityParameter().split(":");
		String oSrcCharSet = vParam[0];
		String oDestCharSet = vParam[1];
		String[] vField = vParam[2].split(",");
		
		for (int i = 0; i < vField.length; ++i)
		{
			String[] vFieldName = vField[i].trim().split("\\.");
			Object root = oCtx.getField(vFieldName[0]);
			
			if (null != root)
			{
				if (1 < vFieldName.length)
				{
					// Map objects chain
					findAndEncodeObject(root, vFieldName, 1, oSrcCharSet, oDestCharSet);
				}
				else
				{
					oCtx.setField(vField[i], new String(((String)root).getBytes(oSrcCharSet), oDestCharSet));
				}
			}
		}
	}
	
	// root can be a Map or Collection object or their implementing classes
	void findAndEncodeObject(Object node, String[] vFieldName, int nIdx, String oSrcCharSet, String oDestCharSet)
		throws java.io.UnsupportedEncodingException
	{
		if (Collection.class.isInstance(node))
		{
			for (Iterator it = ((Collection)node).iterator(); it.hasNext(); )
			{
				findAndEncodeObject(it.next(), vFieldName, nIdx, oSrcCharSet, oDestCharSet);
			}
		}
		else
		{
			Object obj = ((Map)node).get(vFieldName[nIdx]);
			
			if (null == obj)
			{
				return;
			}
			else if (nIdx < vFieldName.length - 1)
			{
				findAndEncodeObject(obj, vFieldName, nIdx + 1, oSrcCharSet, oDestCharSet);
			}
			else
			{
				String dest = new String(((String)obj).getBytes(oSrcCharSet), oDestCharSet);
				((Map)node).put(vFieldName[nIdx], dest);
			}
		}
	}
}
